﻿#define _CRT_SECURE_NO_WARNINGS
// ↑ 将本行在代码放在第一行可以避免 scanf的报错问题（仅在VS编译器里）

#include"Heap.h"




//【函数声明】
/*算法：数据交换*/void Swap(HpDataType* p1, HpDataType* p2)
{
	HpDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}
/*算法：向下调整(小堆)*/void AdjustDown(HpDataType* a, int n, int root)
{
	int parent = root;
	int child = parent * 2 + 1;
	while (child < n)
	{
		//找出较小孩子
		if (child + 1 < n && a[child + 1] < a[child])
		{
			child++;
		}
		//交换
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
/*算法：向上调整(小堆)*/void AdjustUp(HpDataType* a,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child]<a[parent])
		{
			Swap(&a[child],& a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

/*初始化*/void HeapInit(Hp* php, HpDataType* a, int n)
{
	//创建空间
	php->a = (HpDataType*)malloc(sizeof(HpDataType) * n);
	//放入数据
	memcpy(php->a, a, sizeof(HpDataType) * n);
	php->size = n;
	php->capacity = n;
	//构建堆
	for (int i = (n - 2) / 2; i >= 0; --i)
	{
		AdjustDown(php->a, php->size, i);
	}
}
/*空间销毁*/void HeapDestroy(Hp* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}
/*数据插入*/void HeapPush(Hp* php, HpDataType x)
{
	assert(php);
	if (php->capacity == php->size)
	{
		php->capacity *= 2;
		HpDataType* tmp = (HpDataType*)realloc(php->a, sizeof(HpDataType) * php->capacity);
		php->a = tmp;
	}
	php->a[php->size++] = x;
	AdjustUp(php->a, php->size - 1);
}
/*数据删除：删除堆顶的数据*/void HeapPop(Hp* php)
{
	assert(php);
	assert(php->size>0);
	Swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;
	AdjustDown(php->a, php->size, 0);
}
/*堆顶数据提取*/HpDataType HeapTop(Hp* php)
{
	assert(php);
	assert(php->size > 0);

	return php->a[0];
}

/*利用堆快速排序*/void HeapSort(int* a, int n)
{
	for (int i = (n - 2) / 2; i >= 0; --i)
	{
		AdjustDown(a, n, i);
	}
	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		AdjustDown(a, end, 0);
		--end;
	}
}



/*打印*/void HeapPrint(Hp* php)
{
	int i = 0;
	int j = 0;
	while (i < php->size)
	{
		j = i;
		while (j <= 2 * i && j < php->size)
		{

			printf("%d ", php->a[j]);
			j++;
		}
		i = i * 2;
		i++;

		printf("\n");
	}
}
/*高度计算*/int HeapHigh(Hp* php)
{
	assert(php);
	int high = 0;
	int i = php->size;
	if (i == 0)return 0;
	while (i > 0)
	{
		i = (i - 1) / 2;
		high++;
	}
	high++;
	return high;
}

/*打印*/void HeapPrint2(Hp* php)
{
	int i = 0;
	int j = 0;
	int h = pow(2,HeapHigh(php));
	while (i < php->size)
	{
		//前端空格
		if(h>1)
		{
			for (int x = 0; x <h;x++)
			{
				printf(" ");
			}
	

		}
		j = i;
		while (j <= 2 * i && j < php->size)
		{

			printf("%d ", php->a[j]);
			j++;
			//中间空格
				for (int x = 0; x <(2 * h)+1; x++)
				{
					printf(" ");
				}

			
		}
		i = i * 2;
		i++;
		h = (h - 1) / 2;
		printf("\n");
	}
}